const express = require("express");
const { Category, Course } = require("../../models");
const router = express.Router();
const Sequelize = require("sequelize");
const { NotFoundError } = require("../../utils/errors");
const { success, failure } = require("../../utils/responses");
const Op = Sequelize.Op;

/**
 * 获取分类列表
 * GET /admin/categories
 */
router.get("/", async function (req, res) {
  try {
    const query = req.query;
    const currentPage = Math.abs(Number(query.currentPage)) || 1;
    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const offset = (currentPage - 1) * pageSize;
    const condition = {
      order: [["id", "ASC"]],
      offset,
      limit: pageSize,
    };
    if (query.name) {
      condition.where = {
        name: {
          [Op.like]: `%${query.name}%`,
        },
      };
    }
    const categories = await Category.findAndCountAll(condition);
    success(res, "Get categories successfully", {
      categories: categories.rows,
      total: categories.count,
      currentPage,
      pageSize,
    });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 根据id获取分类
 * GET /admin/categories/:id
 */
router.get("/:id", async function (req, res) {
  try {
    const category = await getCategory(req);
    success(res, "Get category successfully", { category });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 创建分类
 * POST /admin/categories
 */
router.post("/", async function (req, res) {
  try {
    const body = filterBody(req.body);
    const category = await Category.create(body);
    success(res, "Create category successfully", { category }, 201);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 删除分类
 * DELETE /admin/categories/:id
 */
router.delete("/:id", async function (req, res) {
  try {
    const category = await getCategory(req);
    const count = await Course.count({
      where: { categoryId: req.params.id },
    });
    if (count > 0) {
      throw new Error("该分类下存在课程，不能删除");
    }
    await category.destroy();
    success(res, "Delete category successfully");
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新分类
 * PUT /admin/categories/:id
 */
router.put("/:id", async function (req, res) {
  try {
    const category = await getCategory(req);
    await category.update(filterBody(req.body));
    success(res, "Update category successfully", { category });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 公共方法： 过滤请求体
 */
function filterBody(body) {
  const { name, rank } = body;
  return {
    name,
    rank,
  };
}

/**
 * 公共方法： 查询当前分类
 */
async function getCategory(req) {
  const { id } = req.params;
  const category = await Category.findByPk(id);
  if (!category) {
    throw new NotFoundError(`ID: ${id}的分类未找到`);
  }
  return category;
}

module.exports = router;
